#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <net/if.h> // struct ifconf

int main( void ) {
	struct ifreq ir[5]; // 获取到的网络接口
	struct ifconf conf;
	conf.ifc_len = sizeof(ir);
	conf.ifc_req = ir;

	int fd = socket(AF_INET, SOCK_STREAM, 0);
	int ret = ioctl(fd, SIOCGIFCONF, &conf);

	int cnt = conf.ifc_len/sizeof(struct ifreq); // 获取接口个数
	int i;
	for (i=0; i<cnt; i++) {
		printf("%s\n", ir[i].ifr_name);
		struct ifreq req;
		memset(&req, 0x00, sizeof(req));
		memcpy(req.ifr_name, ir[i].ifr_name, strlen(ir[i].ifr_name));
		// 获取接口信息
		struct sockaddr_in *addr;
		ret = ioctl(fd, SIOCGIFDSTADDR, &req);
		addr = (struct sockaddr_in*)&req.ifr_addr;
		printf("\taddr : %s\n", inet_ntoa(addr->sin_addr));

		ret = ioctl(fd, SIOCGIFNETMASK, &req);
		addr = (struct sockaddr_in*)&req.ifr_netmask;
		printf("\tnetmask: %s\n", inet_ntoa(addr->sin_addr));

		ret = ioctl(fd, SIOCGIFBRDADDR, &req);
		addr = (struct sockaddr_in*)&req.ifr_addr;
		printf("\tbroadcast : %s\n", inet_ntoa(addr->sin_addr));

		ret = ioctl(fd, SIOCGIFMTU, &req);
		printf("\tmtu : %d\n", req.ifr_mtu);

		ret = ioctl(fd, SIOCGIFHWADDR, &req);
		unsigned char arp[6];
		memcpy(arp, req.ifr_hwaddr.sa_data, 6);
		printf("\tMAC : %02x:%02x:%02x:%02x:%02x:%02x\n", arp[0],arp[1],arp[2],arp[3],arp[4],arp[5],arp[6]);
	}
	getchar();
}
